package android.map;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class Main extends MapActivity {

    public GeoPoint p,pointGPS;
    public MapController mc;
    MapView mapView;
    List<Overlay> listOfOverlays;
    ArrayList<GeoPoint> listGeoP;
    class MapOverlay extends com.google.android.maps.Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when){
        	for(int i=0;i<listGeoP.size();i++){
        		super.draw(canvas, mapView, shadow);   
            	//---translate the GeoPoint to screen pixels---
        	
            	Point screenPts = new Point();
            	mapView.getProjection().toPixels(listGeoP.get(i), screenPts);
            	//---add the marker---
            	Bitmap bmp = BitmapFactory.decodeResource( getResources(), R.drawable.select);            
            	canvas.drawBitmap(bmp, screenPts.x, screenPts.y-32, null);    
        	}
            return true;
        }
        
    } 
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mapView = (MapView) findViewById(R.id.mapview);
        listGeoP = new ArrayList<GeoPoint>(); 
        mapView.displayZoomControls(true); 
        mapView.setStreetView(true);
        mapView.setSatellite(true);
        mapView.setTraffic(true);
        mapView.setBuiltInZoomControls(true);
        mc = mapView.getController();
        String coordinates[] = {"-34.972863","-71.208395"}; 
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);
 
        p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
        listGeoP.add(p);
        mc.animateTo(p);
        mc.setZoom(14); 
        MapOverlay mapOverlayInicial = new MapOverlay();
        listOfOverlays = mapView.getOverlays();
        listOfOverlays.add(mapOverlayInicial);   
        mapView.invalidate();
        
        
        
        LocationManager l =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
        LocationListener locationListener = new LocationListener() {
			
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {}
			
			@Override
			public void onProviderEnabled(String provider) {}
			
			@Override
			public void onProviderDisabled(String provider) {}
		
			@Override
			public void onLocationChanged(Location l) {
				if (l != null) {
						pointGPS = new GeoPoint((int) (l.getLatitude() * 1E6), (int) (l.getLongitude() * 1E6));
				        mc.animateTo(pointGPS);
				        listGeoP.add(pointGPS);
				        MapOverlay mapOverlay = new MapOverlay();
				        listOfOverlays = mapView.getOverlays();
				        listOfOverlays.add(mapOverlay);   
				        mapView.invalidate();  
				        DrawPath(listGeoP.get(listGeoP.size()-2), listGeoP.get(listGeoP.size()-1), Color.GREEN, mapView);
                }
			}
		};
		l.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
		 
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	// TODO Auto-generated method stub
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.principal, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.MnuOpc1:
                return true;
            case R.id.MnuOpc2:
            	showDialog();
                return true;
            case R.id.SubMnuOpc1:
            	mapView.setStreetView(false);
                mapView.setSatellite(true);
                mapView.setTraffic(false);
            	return true;
            case R.id.SubMnuOpc2:
            	mapView.setStreetView(true);
                mapView.setSatellite(false);
                mapView.setTraffic(true);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	
	private void DrawPath(GeoPoint src,GeoPoint dest, int color, MapView mMapView01)
	{
		// connect to map web service
		StringBuilder urlString = new StringBuilder();
		urlString.append("http://maps.google.com/maps?f=d&hl=en");
		urlString.append("&saddr=");//from
		urlString.append( Double.toString((double)src.getLatitudeE6()/1.0E6 ));
		urlString.append(",");
		urlString.append( Double.toString((double)src.getLongitudeE6()/1.0E6 ));
		urlString.append("&daddr=");//to
		urlString.append( Double.toString((double)dest.getLatitudeE6()/1.0E6 ));
		urlString.append(",");
		urlString.append( Double.toString((double)dest.getLongitudeE6()/1.0E6 ));
		urlString.append("&ie=UTF8&0&om=0&output=kml");
		Log.d("xxx","URL="+urlString.toString());
		
		// get the kml (XML) doc. And parse it to get the coordinates(direction route).
		Document doc = null;
		HttpURLConnection urlConnection= null;
		URL url = null;
		try
		{
			url = new URL(urlString.toString());
			urlConnection=(HttpURLConnection)url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.connect();
		
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(urlConnection.getInputStream());

			if(doc.getElementsByTagName("GeometryCollection").getLength()>0)
			{
				String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ;
				Log.d("xxx","path="+ path);
				String [] pairs = path.split(" ");
				String[] lngLat = pairs[0].split(","); 
				
				GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));

				GeoPoint gp1;
				GeoPoint gp2 = startGP;
				for(int i=1;i<pairs.length;i++) 
				{
					lngLat = pairs[i].split(",");
					gp1 = gp2;
					gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
					mMapView01.getOverlays().add(new MyOverLay(gp1,gp2,color));
					Log.d("xxx","pair:" + pairs[i]);
				}
			}
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (ParserConfigurationException e)
		{
			e.printStackTrace();
		}
		catch (SAXException e)
		{
			e.printStackTrace();
		}
	}
	
	void showDialog(){
    	AlertDialog.Builder alert = new AlertDialog.Builder(this);
 	   	alert.setTitle("Advertencia");
    	alert.setMessage("¿Desea realmente salir de la aplicación?");
 	    alert.setCancelable(false);
 	    alert.setPositiveButton("Sí", new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int id) {
                  salir();
              }
         	 });
 	      alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
 	              public void onClick(DialogInterface dialog, int id) {
 	                   dialog.cancel();
 	              }
 	          });
 	   AlertDialog mensaje = alert.create();
 	   mensaje.show();
    }
    
	public void salir(){
        setResult(RESULT_OK);
        finish();
    }
	
}